﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace Nirvana
{
    public class UnitySingleton<T> : MonoBehaviour where T : MonoBehaviour
    {
        private static T instance;
        public static T Instance
        {
            get
            {
               CheckInstance();
                return instance;
            }
        }
        public static bool InstanceExisted
        {
            get
            {
                return instance != null;
            }
        }


        public static void CheckInstance()
        {
            if (instance == null)
            {
                GameObject gameObject = new GameObject(typeof(T).Name, typeof(T));
                if (Application.isPlaying)
                {
                    UnityEngine.Object.DontDestroyOnLoad(gameObject);
                }
                else
                {
#if UNITY_EDITOR
                    gameObject.hideFlags = HideFlags.HideAndDontSave;
                    EditorApplication.playModeStateChanged += (state)=> {
                        if (instance != null)
                        {
                            UnityEngine.Object.DestroyImmediate(instance.gameObject);
                            instance = null;
                        }
                    };
#endif
                }
                instance = gameObject.GetComponent<T>();
            }
        }




        protected void OnApplicationQuit()
        {
            if (instance != null)
            {
                UnityEngine.Object.DestroyImmediate(instance.gameObject);
            }
        }

        protected void OnDestroy()
        {
            instance = null;
            OnDispose();
        }

        protected virtual void OnDispose()
        {

        }

    }
}

